/*
Copyright (c) 2009, Dan Hagerstrand and contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of Cirrus Creative nor the names of its
  contributors may be used to endorse or promote products derived from this
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstdlib>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <bitset>

#include "../include/beng/System.h"

BengSystem::~BengSystem(void)
{
    this->consprint("\n\n----------------\n\nSystem shutdown.\n");

    if (this->scene)
    {
        this->consprint("\nClearing scene...");
        delete this->scene;
    }

    this->consprint("\nFreeing resources...");
    delete this->spriteResourceList;
    delete this->sampleResourceList;

    this->interface->deinit();
    delete this->interface;
}

// Displays a message without formatting it.
void BengSystem::consprint(const char *message)
{
    //cons_addline(textbuffer); //Old C Beng code. TODO: Replace with newer function.
    fprintf(this->logFile, "%s", message);
    std::printf("%s", message);
    fflush(this->logFile);
}

// Displays a message in printf format, sending it to stdout, console, and log.
void BengSystem::consprintf(const char *format, ...)
{
    char textbuffer[512];

    va_list ap;

    va_start(ap, format);
    vsprintf(textbuffer, format, ap);
    va_end(ap);

    //cons_addline(textbuffer); //Old C Beng code. TODO: Replace with newer function.
    fprintf(this->logFile,  "%s", textbuffer);
    std::printf( "%s", textbuffer);
    fflush(this->logFile);
}

// Displays an error either in a pop-up or console, and closes the program if need-be.
// In the future, warnings can be suppressed
void BengSystem::giveError(int severity, const char *format, ...)
{
    char textbuffer[512];
    va_list ap;

    va_start(ap, format);
    vsprintf(textbuffer, format, ap);
    va_end(ap);

    // The actual failure exit doesn't happen until the end, to give priority to the console output.
    switch (severity)
    {
        case BENG_ERROR_FATAL:
            this->consprintf("\n\n!!ENCOUNTERED A FATAL ERROR!!\n%s\n\nNow aborting!\n", textbuffer);
            break;

        case BENG_ERROR_STANDARD:
            this->consprintf("\n\nERROR! %s\n", textbuffer);
            break;

        case BENG_ERROR_WARNING:
            this->consprintf("\n\nWARNING: %s\n", textbuffer);
            break;
    }

    this->interface->displayError_(severity, textbuffer);

    if (severity == BENG_ERROR_FATAL)
        exit(EXIT_FAILURE);

}

const char *BengSystem::getName(void)
{
    return this->gameName.string;
}

void BengSystem::setName(const char *name)
{
    this->gameName.set(name);
    this->interface->updateName_();
}

void BengSystem::getWindowSize(int &xOut, int &yOut)
{
    xOut = this->windowW;
    yOut = this->windowH;
}

// Closes any existing scene and creates a blank one which can then be manually provided layers, objects...
int BengSystem::newScene(const char *scenename)
{
    this->consprintf("\n\n----------------\n\nRequested new scene:\n%s", scenename);

    if (!this->interface->isInit)
    {
        this->giveError(BENG_ERROR_STANDARD, "You must load the interface before loading any scene.");
        return 0;
    }

    if (this->scene)
    {
        this->consprint("\n\nUnloading old scene...");
        delete this->scene;
        this->scene = NULL;
        this->consprint("\nDone.");
    }

    this->consprint("\n\nCreating new scene...");

    this->scene = new BengScene();
    this->scene->attachToSystem(this);

    if (!this->scene)
        this->giveError(BENG_ERROR_FATAL, "Failed to create scene. You may be out of memory.");

    this->scene->setName(scenename);

    this->consprint("\nSuccess!");

    return 1;
}

// Called by the host program when it's time to start the game.
int BengSystem::mainLoop(void)
{
    std::bitset<2> result;

    this->consprint("\n\nEntering main loop.\n\n");

    if (!this->scene)
    {
        this->giveError(BENG_ERROR_STANDARD, "Attempted to enter main loop with no scene loaded.\nExiting main loop abnormally.");
        return 0;
    }

    // The actual main loop
    while (!this->exitLoop_)
    {
        result.reset();
        this->interface->startLoop(result);

        // result returns flags that indicate what to compute

        if (result[BENG_INTERFACE_TIMER_PROCESS])
        {
            this->scene->process();
            //printf("\nTics left: %i", this->interface->ticQueue_);
            //rest((this->interface->tics_ / 12) % 100); // Used to bugtest frameskip throttling
        }
        if (result[BENG_INTERFACE_TIMER_DRAW])
        {
            //rest(48); // Used to bugtest frameskip
            this->interface->iGfx->drawLoop();
            this->interface->fpsTics_++;
            this->interface->fpsTotalTics_++;
        }
    }

    this->consprint("\nExiting main loop normally.");

    return 1;
}
